<!-- 修改页面弹窗 -->
<template>
  <div>
    <el-dialog :title="editTitle" :visible.sync="show" v-if="show" :close-on-click-modal="false" width="900px" top="6vh" v-dialogDrag @close="cancel()">
      <div class="dialog-container">
        <el-form :model="editForm" size="small" :rules="FormRules" ref="editForm" label-width="150px">
          <el-row>
            <el-col :span="11">
              <el-form-item label="用户编码" prop="yhbm">
                <el-input v-model="editForm.yhbm"></el-input>
              </el-form-item>

              <el-form-item label="投运日期" prop="tyrq">
                <el-date-picker type="date" v-model="editForm.tyrq" value-format="yyyy-MM-dd" style="width:100%"></el-date-picker>
              </el-form-item>

              <el-form-item label="注册日期" prop="zcrq">
                <el-date-picker type="date" v-model="editForm.zcrq" value-format="yyyy-MM-dd" style="width:100%"></el-date-picker>
              </el-form-item>

              <el-form-item label="电缆长度(km)" prop="dlcd">
                <el-input v-model="editForm.dlcd" @change="getXlhj()"></el-input>
              </el-form-item>

              <el-form-item label="架空线路长度(km)" prop="jkcd">
                <el-input v-model="editForm.jkcd" @change="getXlhj()"></el-input>
              </el-form-item>

              <el-form-item label="线路合计(kM)" prop="xlhj">
                <el-input v-model="editForm.xlhj" disabled></el-input>
              </el-form-item>

              <el-form-item label="变压器台数" prop="bts">
                <el-input v-model="editForm.bts"></el-input>
              </el-form-item>

              <el-form-item label="载容比" prop="zrb">
                <el-input v-model="editForm.zrb"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="11">
              <el-form-item label="用户名称" prop="yhmc">
                <el-input v-model="editForm.yhmc"></el-input>
              </el-form-item>

              <el-form-item label="电压等级(kV)" prop="dydjm">
                <el-select v-model="editForm.dydjm" @change="getDydj" style="width:100%">
                  <el-option
                    v-for="item in dydjCombo"
                    :key="item.value"
                    :label="item.text"
                    :value="item.value">
                  </el-option>
                </el-select>
              </el-form-item>

              <el-form-item label="用户性质" prop="yhxzm">
                <el-select v-model="editForm.yhxzm" @change="getYhxz" style="width:100%">
                  <el-option
                    v-for="item in yhxzCombo"
                    :key="item.value"
                    :label="item.text"
                    :value="item.value">
                  </el-option>
                </el-select>
              </el-form-item>

              <el-form-item label="规划特征" prop="ghtz">
                <el-select v-model="editForm.ghtz" style="width:100%">
                  <el-option
                    v-for="item in ghtzCombo"
                    :key="item.value"
                    :label="item.text"
                    :value="item.value">
                  </el-option>
                </el-select>
              </el-form-item>

              <el-form-item label="是否双电源" prop="issdy">
                <el-select v-model="editForm.issdy" @change="getSdyrl()" style="width:100%">
                  <el-option
                    v-for="item in issdyCombo"
                    :key="item.value"
                    :label="item.text"
                    :value="item.value">
                  </el-option>
                </el-select>
              </el-form-item>

              <el-form-item label="双电源容量(kVA)" prop="sdyrl">
                <el-input v-model="editForm.sdyrl" disabled></el-input>
              </el-form-item>

              <el-form-item label="变压器容量(kVA)" prop="brl">
                <el-input v-model="editForm.brl" @change="getSdyrl()"></el-input>
              </el-form-item>

              <el-form-item label="行政区划" prop="xzqh">
                <el-input v-model="editForm.xzqh" disabled>
                  <el-button slot="append" type="primary" class="button-choose" @click="selectXzqh">选择</el-button>
                </el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="22">
              <el-form-item label="用户描述" prop="yhms">
                <el-input v-model="editForm.yhms"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
      <div slot="footer" class="foot-container">
        <el-button type="primary" size="mini" @click="edit('editForm')">确 定</el-button>
        <el-button type="primary" size="mini" @click="cancel()">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 选择行政区划 -->
    <GetXzqh ref="getXzqhRef" @handleGetXzqh="handleGetXzqh"></GetXzqh>
  </div>
</template>

<script>
  import { getDictCombo } from "@/api/tools/dict";
  import { checkChar } from "@/utils/formValidate";
  import { compareDate,checkSpecialKey,floatAdd } from "@/utils/validate";
  import { objectCopy } from "@/utils/index";
  import { checkUnique,getZcgyyhsjById,editZcgyyhsj } from "@/api/sjwh/zcgy";
  import { getUserInfo } from "@/utils/utilInfo.js";
  import GetXzqh from "@/dialogCommom/GetXzqh";

  export default {
    name: 'zcgyyhEdit',
    components: {
      GetXzqh: GetXzqh,
    },
    data() {
      // 验证用户编码唯一
      const validateYhbm = (rule, value, callback) => {
        if (value) {
          let reg = /^([\u4e00-\u9fa5]{2})([0-9]{3})([\s\S]{0,7})$/
          if (checkSpecialKey(value)) {
            if (reg.test(value)) {
              let vo = {
                dwbm: this.editFormHide.dwbm,
                zcrq: this.editForm.zcrq,
                yhbm: value,
                oid: this.editFormHide.id,
              }
              // 用户编码唯一性验证
              checkUnique(vo).then(res => {
                if (res.code == 0 && res.data) {
                  callback()
                } else {
                  callback('用户编码已经存在')
                }
              })
            } else {
              callback('2汉字+3数字+0~7字符')
            }
          } else {
            callback('禁止输入空格~!#$%^&等特殊字符')
          }
        }
      }
      // 4位整数验证
      const numberLen4 = (rule, value, callback) => {
        let val = value + ''
        if (val) {
          if (/(^([1-9]{1})([0-9]{0,3})$)|(^0$)/.test(val)) {
            callback()
          } else {
            callback('精度：4位整数')
          }
        }
      }
      // 10位整数验证
      const numberLen10 = (rule, value, callback) => {
        let val = value + ''
        if (val) {
          if (/(^([1-9]{1})([0-9]{0,9})$)|(^0$)/.test(val)) {
            callback()
          } else {
            callback('精度：10位整数')
          }
        }
      }
      // 6位整数数6位小数验证
      const floatLen66 = (rule, value, callback) => {
        let val = value + ''
        if (val) {
          let reg = /(^([1-9]{1})([0-9]{0,5})$)|(^([1-9]{1})([0-9]{0,5})[\.]{1}([0-9]{1,6})$)|(^0[\.]{1}[0-9]{1,6}$)|(^0$)/
          if (reg.test(val)) {
            callback()
          } else {
            callback('精度：整数6位，小数6位')
          }
        }
      }
      // 4位小数验证
      const floatLen04 = (rule, value, callback) => {
        let val = value + ''
        if (val) {
          let reg = /^(0[\.]{1}[0-9]{1,4}$)|(^1$)/
          if (reg.test(val)) {
            callback()
          } else {
            callback('精度：小数4位且<=1')
          }
        }
      }
      return {
        editTitle: '高压用户修改',
        show: false,
        yhxzCombo: [],
        dydjCombo: [],
        issdyCombo: [],
        ghtzCombo: [],
        editForm: {
          yhbm: '',
          yhmc: '',
          yhxzm: '',
          dydjm: '',
          dlcd: '',
          jkcd: '',
          xlhj: '',
          xzqh: '',
          ghtz: '',
          issdy: '',
          bts: '',
          brl: '',
          sdyrl: '',
          zrb: '',
          yhms: '',
          tyrq: '',
          zcrq: '',
        },
        editFormHide: { // 隐藏属性
          id: '',
          dwbm: '',
          dwmc: '',
          dwxzm: '',
          dwxz: '',
          yhxz: '',
          dydj: '',
          xzqhm: '',
          czy: '',
        },
        FormRules: {
          yhbm: [
            {required: true, message: '请输入用户编码', trigger: 'blur'},
            {validator: validateYhbm, trigger: 'blur'}
          ],
          yhmc: [
            {required: true, message: '请填写用户名称', trigger: 'blur'},
            {validator: checkChar, trigger: 'blur'}
          ],
          dlcd: [
            {required: true, message: '请填写电缆线路长度', trigger: 'blur'},
            {validator: floatLen66, trigger: 'blur'}
          ],
          jkcd: [
            {required: true, message: '请填写架空线路长度', trigger: 'blur'},
            {validator: floatLen66, trigger: 'blur'}
          ],
          bts: [
            {required: true, message: '请填写变压器台数', trigger: 'blur'},
            {validator: numberLen4, trigger: 'blur'}
          ],
          brl: [
            {required: true, message: '请填写变压器容量', trigger: 'blur'},
            {validator: numberLen10, trigger: 'blur'}
          ],
          zrb: [
            {required: true, message: '请填写载容比', trigger: 'blur'},
            {validator: floatLen04, trigger: 'blur'}
          ],
          issdy: [{required: true, message: '请选择是否双电源', trigger: 'change'}],
          yhxzm: [{required: true, message: '请选择用户性质', trigger: 'change'}],
          dydjm: [{required: true, message: '请选择电压等级', trigger: 'change'}],
          ghtz: [{required: true, message: '请选择规划特征', trigger: 'change'}],
          tyrq: [{required: true, message: '请选择投运日期', trigger: 'change'}],
          zcrq: [{required: true, message: '请选择注册日期', trigger: 'change'}],
          yhms: [{validator: checkChar, trigger: 'blur'}],
        },
      }
    },
    props: {
      editData: {
        type: Object,
        default: function() {
          return {};
        }
      }
    },
    watch: {
      editData: {
        deep: true,
        handler(newVal, oldVal) {
          if (newVal.show) {
            this.show = newVal.show
            this.getFormData(newVal.id) // 根据ID查询数据
          }
        }
      }
    },

    created() {
    },

    mounted() {
      this.dictOptData(); // 获取字典值
    },

    methods: {
      // 获取表单数据
      getFormData(id) {
        const that = this
        getZcgyyhsjById(id).then(res => {
          if (res.code == 0) {
            objectCopy(res.data,that.editForm) // 复制属性
            objectCopy(res.data,that.editFormHide) // 复制属性
            that.editFormHide.czy = getUserInfo.userName;
          } else {
            that.$message.error(res.message)
          }
        })
      },
      edit() {
        this.$refs['editForm'].validate((valid) => {
          if(valid) {
            if(compareDate(this.editForm.tyrq,this.editForm.zcrq)){
              this.$message.warning("注册日期不能早于投运日期！");
              return;
            }
            this.checkYhmc();
          }else{
            this.$message.warning( "请检查填写数据项是否缺失或错误！");
          }
        });
      },
      save() {
        // 提交数据
        let zcGyyhsj = Object.assign({}, this.editForm, this.editFormHide); // 合并属性
        editZcgyyhsj({zcGyyhsj}).then(res => {
          if (res.code == 0) {
            this.$message.success( "修改成功！");
            this.cancel();
            this.$parent.refresh(); // 调用父页面方法
          } else {
            this.$message.error("修改失败！");
          }
        });
      },
      cancel() {
        this.show = false;
        this.$refs['editForm'].resetFields(); // 重置表单
        this.editFormHide = {};
      },
      // 获取字典下拉数据
      async dictOptData() {
        let yhxzRes = await getDictCombo({"typeCode":"dict_yhxz"});
        let dydjRes = await getDictCombo({"typeCode":"dict_dydj_gy"});
        let ghtzRes = await getDictCombo({"typeCode":"dict_ghtz"});
        let issdyRes = await getDictCombo({"typeCode":"dict_bool"});
        if(yhxzRes.code == 0){
          this.yhxzCombo = yhxzRes.data;
        }
        if(dydjRes.code == 0){
          this.dydjCombo = dydjRes.data;
        }
        if(ghtzRes.code == 0){
          this.ghtzCombo = ghtzRes.data;
        }
        if(issdyRes.code == 0){
          this.issdyCombo = issdyRes.data;
        }
      },
      getYhxz(val){
        let obj = {};
        obj = this.yhxzCombo.find((item)=>{ // 这里的yhxzCombo就是上面遍历的数据源
          return item.value === val; // 筛选出匹配数据
        });
        this.editFormHide.yhxz = obj.text;
      },
      getDydj(val){
        let obj = {};
        obj = this.dydjCombo.find((item)=>{
          return item.value === val; // 筛选出匹配数据
        });
        this.editFormHide.dydj = obj.text;
      },
      getXlhj() {
        let dlcd = 0;
        let jkcd = 0;
        if(this.editForm.dlcd!=""){
          dlcd = parseFloat(this.editForm.dlcd);
        }
        if(this.editForm.jkcd!=""){
          jkcd = parseFloat(this.editForm.jkcd);
        }
        this.editForm.xlhj = floatAdd(dlcd,jkcd);
      },
      getSdyrl() {
        const that = this;
        if(that.editForm.issdy == "1" && that.editForm.brl != ""){
          that.editForm.sdyrl = that.editForm.brl;
        }else{
          that.editForm.sdyrl = 0;
        }
      },
      /* 选择行政区划 */
      selectXzqh() {
        const that = this
        that.$refs.getXzqhRef.openXzqh()
      },
      /* 行政区划选择组件回传 */
      handleGetXzqh(val) {
        const that = this
        that.editForm.xzqh = val.name
        that.editFormHide.xzqhm = val.code
      },
      // 确认提示
      checkYhmc() {
        let vo = {
          dwbm: this.editFormHide.dwbm,
          zcrq: this.editForm.zcrq,
          yhmc: this.editForm.yhmc,
          oid: this.editFormHide.id,
        }
        // 用户名称唯一性验证
        checkUnique(vo).then(res => {
          if (res.code == 0) {
            if(res.data) {
              this.checkXlhj();
            }else{
              this.$confirm(
                '线路名称已经被使用,需要继续保存吗?',
                '提示',
                {
                  confirmButtonText: '确定',
                  cancelButtonText: '取消',
                  type: 'warning'
                }
              ).then(() => {
                this.checkXlhj();
              })
            }
          }
        })
      },
      // 确认提示
      checkXlhj() {
        if (this.editForm.xlhj == 0) {
          this.$confirm(
            '线路合计为0,需要继续保存吗?',
            '提示',
            {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            }
          ).then(() => {
            this.save();
          })
        }else{
          this.save();
        }
      },
    }
  }
</script>

<style scoped lang='scss'>
  /deep/ .el-dialog__body {
    padding-top: 20px;
    padding-bottom: 1px;
    border-top: 1px solid #e8eaec;
    border-bottom: 1px solid #e8eaec;
  }
  /deep/ .el-dialog__header {
    padding: 10px 10px 10px;
  }
  /deep/ .el-dialog__footer {
    padding: 10px 10px 10px;
  }
  .dialog-container{
    height: 60vh;
    overflow: auto;
  }
  .button-choose {
    background-color: #409EFF !important;
    border-color: #409EFF !important;
    color: #ffffff !important;
  }
</style>
